package cn.gok.controller;

import cn.gok.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @author: chen fan
 * @since: 2022/11/7 17:45
 * @description:
 */
@Controller
@RequestMapping("/fileUp")
public class FileUPController {


    /**
        测试SpringMVC实现单文件上传
            在Spring MVC中，一个文件就是一个multipartFile对象
     */
    @RequestMapping("/file.do")
    public String fileUp(@RequestParam("file") MultipartFile multipartFile,
                         User user,
                         HttpServletRequest request) throws IOException {

        //1、创建文件上传的路径
        String imagePath = request.getServletContext().getRealPath("") + "static/images";
        File file = new File(imagePath);
        if (!file.exists()){
            file.mkdirs();
        }


        //2、对文件进重命名
        //获取原文件名
        String originalFilename = multipartFile.getOriginalFilename();
        //获取文件的后缀名
        String suffixName = originalFilename.substring(originalFilename.lastIndexOf("."));
        //产生新的文件名
        String newFileName = UUID.randomUUID().toString() + suffixName;


        //3、将上传的文件输出到指定File中
        File file1 = new File(imagePath + File.separator + newFileName);
        multipartFile.transferTo(file1);

        System.out.println(user);

        return "success";
    }

    @RequestMapping("/files.do")
    public String fileUps(@RequestParam("file") MultipartFile[] multipartFiles,
                          User user,
                          HttpServletRequest request,
                          HttpSession session
                          ) throws IOException {
        System.out.println(user);

        //1、创建文件上传的路径
        String imagePath = request.getServletContext().getRealPath("") + "static/images";
        File file = new File(imagePath);
        if (!file.exists()){
            file.mkdirs();
        }


        //2、对文件进重命名
        for (int i = 0; i< multipartFiles.length; i++) {
            MultipartFile mf = multipartFiles[i];

            //获取原文件名
            String originalFilename = mf.getOriginalFilename();
            //获取文件的后缀名
            String suffixName = originalFilename.substring(originalFilename.lastIndexOf("."));
            //产生新的文件名
            String newFileName = UUID.randomUUID().toString() + suffixName;


            session.setAttribute("fileName"+i,newFileName);


            //3、将上传的文件输出到指定File中
            File file1 = new File(imagePath + File.separator + newFileName);
            mf.transferTo(file1);

        }

        return "success";

    }




}
